﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ODS.Config;
using ODS.Utils;
using System.IO;
using ODS.Model;
using System.Xml.Linq;
using System.Windows;

namespace ODS.WebService.DeviceData
{
    public class FindDeviceMessagesService
    {
        static bool IsAuthenticated = true;

        public static async Task<InfoResult> FindDeviceMessages(String imei, DateTime minDate, DateTime maxDate, int page, int offset)
        {
            String minDateFormat = minDate.ToString("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            String maxDateFormat = maxDate.ToString("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

            String url = Constants.SERVER_URL + "/devices/" + imei + "/messages/find";
            String body = String.Format("<messageFilter><minGeneratedAt>{0}</minGeneratedAt><maxGeneratedAt>{1}</maxGeneratedAt><pageFilter><size>{2}</size><offset>{3}</offset></pageFilter></messageFilter>",
                                            minDateFormat,
                                            maxDateFormat,
                                            page,
                                            offset);

            InfoResult result;
            try
            {
                Stream xmlStream = await RESTfulService.HTTPPostRequest(url, body);
                List<MessageModel> obj = ParseXML(xmlStream);

                #region check authenticate
                if (!IsAuthenticated)
                {
                    InfoResult result_login = await Login_Logout.LoginService.loginService(App.userLogin.UserLoginName, App.userLogin.UserPassword);
                    if (result_login.IsSuccess)
                    {
                        if ((String)result_login.ReturnedObject == Constants.SUCCESS)
                        {
                            IsAuthenticated = true;

                            return await FindDeviceMessages(imei, minDate, maxDate, page, offset);
                        }
                        else
                        {
                            MessageBox.Show((String)result_login.ReturnedObject);
                            App.BackToLoginPage();

                        }
                    }
                    else
                    {
                        MessageBox.Show(result_login.Error);
                        App.BackToLoginPage();

                    }


                }
                #endregion

                result = new InfoResult(null, obj);
            }
            catch (Exception ex)
            {
                result = new InfoResult(ex.Message, null);
            }

            return result;
        }

        private static List<MessageModel> ParseXML(Stream xmlStream)
        {
            List<MessageModel> listMessageModel = new List<MessageModel>();

            XDocument doc = XDocument.Load(xmlStream);

            var Authenticate = (from authen in doc.Descendants("unauthorized")
                                select new
                                {

                                }).FirstOrDefault();
            if (Authenticate != null)
            {
                IsAuthenticated = false;
                return null;
            }

            var messages = from message in doc.Descendants("messageDetails")
                           select new
                           {
                               GeneratedAt = message.Element("generatedAt").Value,
                               Heading = message.Element("heading").Value,
                               Ignition = message.Element("ignition").Value,
                               Latitude = message.Element("latitude").Value,
                               Longitude = message.Element("longitude").Value,
                               Odometer = message.Element("odometer").Value,
                               ReceivedAt = message.Element("receivedAt").Value,
                               Speed = message.Element("speed").Value,


                           };
            foreach (var message in messages)
            {
                MessageModel messageModel = new MessageModel();

                messageModel.GeneratedAt = CommonUtil.ParseDateTimeFromString(message.GeneratedAt);
                messageModel.Heading = message.Heading;
                messageModel.Ignition = message.Ignition;
                messageModel.Latitude = message.Latitude;
                messageModel.Longitude = message.Longitude;
                messageModel.Odometer = message.Odometer;
                messageModel.ReceivedAt = CommonUtil.ParseDateTimeFromString(message.ReceivedAt);
                messageModel.Speed = message.Speed;


                listMessageModel.Add(messageModel);
            }


            return listMessageModel;

        }
    }
}
